package com.bwf.lgqingdan.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/11/19.
 */

public class QingdanDbHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "qingdan.db";
    private static final int VERISON = 1;

    public QingdanDbHelper(Context context) {
        super(context, DB_NAME, null, VERISON);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = new CreateTableHelper().table(TableSearchHistoryColumns.TAB_NAME)
                .addColumn(TableSearchHistoryColumns.ID,"integer primary key autoincrement")
                .addColumn(TableSearchHistoryColumns.KEYWORD,"text not null")
                .addColumn(TableSearchHistoryColumns.TIME,"long")
                .buildSql();
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public interface TableSearchHistoryColumns {
        String TAB_NAME = "t_history_keywords";
        String ID = "_id";
        String KEYWORD = "keyword";
        String TIME = "time";
    }

    public static class CreateTableHelper{

        private StringBuffer sb;
        private String tableName;
        private Map<String,String> columnsMap;

        public CreateTableHelper() {
            columnsMap = new HashMap<>();
            sb = new StringBuffer();
        }

        public CreateTableHelper table(String tableName){
            this.tableName = tableName;
            return this;
        }
        public CreateTableHelper addColumn(String columnName,String info){
            columnsMap.put(columnName,info);
            return this;
        }
        public String buildSql(){
            sb.append("create table " + tableName + "(");
            Set<String> keySet = columnsMap.keySet();
            for(String columnName:keySet){
                sb.append(columnName + " " + columnsMap.get(columnName) +",");
            }
            if(keySet.size() > 0){
                sb.deleteCharAt(sb.length()-1);
            }
            sb.append(")");
            return sb.toString();
        }
    }
}
